package com.example.serviceheadlines.job;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.serviceheadlines.mapper.HeadlinesMapper;
import com.example.serviceheadlines.service.HeadlinesCategoryService;
import com.example.serviceheadlines.service.HeadlinesService;
import com.tangyuan.common.util.PushAppUtil;
import com.tangyuan.model.*;
import com.tangyuan.vo.Jrtt;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class TimerExampleJob {

    @Autowired
    private HeadlinesCategoryService headlinesCategoryService;

    @Autowired
    private HeadlinesService headlinesService;
    @Autowired
    private HeadlinesMapper headlinesMapper;

    private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @XxlJob("saveHeadlines")
    public void saveHeadlines() {
        log.info("--开始xxl-job启动--saveHeadlines");
        // 创建HttpClient实例
        LambdaQueryWrapper<HeadlinesCategory> query = new LambdaQueryWrapper<>();
        query.isNotNull(HeadlinesCategory::getChannelId);
        query.eq(HeadlinesCategory::getIsDelete, 0);
        List<HeadlinesCategory> headlinesCategories = headlinesCategoryService.list(query);
        for (HeadlinesCategory headline : headlinesCategories) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 创建HttpGet请求
            try {
                TimeUnit.SECONDS.sleep(10);
                HttpGet httpGet = new HttpGet("https://www.toutiao.com/api/pc/list/feed?channel_id=" + headline.getChannelId() + "&min_behot_time="+headline.getMinBeholdTime()+"&offset="+headline.getOffset()+"&refresh_count="+headline.getRefreshCount()+"&category=pc_profile_channel&client_extra_params=%7B%22short_video_item%22%3A%22filter%22%7D&aid=24&app_name=toutiao_web&msToken="+headline.getMsToken()+"&a_bogus="+headline.getABogus()+"");
                httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
                List<Headlines> arrayList = new ArrayList<>();
                // 发送请求并获取响应
                CloseableHttpResponse response = httpClient.execute(httpGet);
                // 获取响应状态码
                if (response.getStatusLine().getStatusCode() != 200) {
                    log.error("获取"+headline.getChannelName()+"信息失败,"+"请求失败;");
                    continue;
                }
                // 读取响应内容
                String responseBody = EntityUtils.toString(response.getEntity());
                Jrtt jrtt = JSONObject.parseObject(responseBody, Jrtt.class);
                if(jrtt == null){
                    log.error("获取"+headline.getChannelName()+"信息失败");
                    continue;
                }
                if (jrtt.getHasMore()) {
                    if (!jrtt.getData().isEmpty()) {
                        for (Jrtt.DataDTO datum : jrtt.getData()) {
                            Headlines headlines = getHeadlines(headline, datum);
                            arrayList.add(headlines);
                        }
                        //去重
                        List<Long> list = arrayList.stream().map(Headlines::getMediaId).collect(Collectors.toList());
                        List<Long> headlines = headlinesMapper.selectMediaIds(list);
                        if(!CollectionUtils.isEmpty(headlines)){
                            Iterator<Headlines> iterator = arrayList.iterator();
                            while (iterator.hasNext()) {
                                Headlines item = iterator.next();
                                if (headlines.contains(item.getMediaId())) {
                                    iterator.remove();
                                }
                            }
                        }
                        if(!CollectionUtils.isEmpty(arrayList)){
                            headlinesService.saveBatch(arrayList);
                        }
                    }
                }
                // 关闭响应对象
                response.close();
            } catch (Exception e) {
                log.error("百家数据爬取失败,分类:"+headline.getChannelName()+"异常:"+e.toString());
            } finally {
                try {
                    // 关闭HttpClient实例
                    httpClient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }
    private static Headlines getHeadlines(HeadlinesCategory headlinesCategory, Jrtt.DataDTO datum) {
        Headlines headlines = new Headlines();
        headlines.setCommentNum(datum.getCommentCount());
        Random random = new Random();
        int randomNum = random.nextInt(4001) + 1000;
        headlines.setReadNum(datum.getReadCount()+randomNum);
        headlines.setRepinCount(datum.getForwardInfo().getForwardCount());
        headlines.setCollectionNum(datum.getRepinCount());
        headlines.setThumpUpNum(datum.getDiggCount());
        headlines.setArticleUrl(datum.getArticleUrl());
        headlines.setMediaInfoName(datum.getMediaInfo().getName());
        headlines.setAvatarUrl(datum.getMediaInfo().getAvatarUrl());
        headlines.setUserId(0L);
        headlines.setCategoryId(headlinesCategory.getId());
        headlines.setMediaId(datum.getTagId());
        List<String> imageList = new ArrayList<String>();
        if (datum.getImageList() != null && !datum.getImageList().isEmpty()) {
            datum.getImageList().forEach(item -> {
                imageList.add(item.getUrl());
            });
        }
        headlines.setImages(StringUtils.join(imageList, ";"));
        headlines.setCreateTime(new Date());
        headlines.setTitle(datum.getTitle());
        headlines.setUrl(datum.getUrl());
        headlines.setChannelId(headlinesCategory.getChannelId());
        headlines.setPublishTime(new Date(datum.getPublishTime() * 1000L));
        return headlines;
    }


    @XxlJob("robotCreateData")
    public void robotCreateData(){
        log.info("机器人生成百家数据任务,开始时间:{}",format.format(new Date()));
        List<Headlines> headlines = headlinesService.getMediaEqualToNullData();
        if(CollectionUtils.isEmpty(headlines)){
            log.info("没有需要机器人点赞的百家数据");
            return;
        }
        //机器人数量
        Random random = new Random();
        for (Headlines headline : headlines) {
            //浏览量  随机66-99
            headline.setReadNum(headline.getReadNum() + random.nextInt(33)+66);
            //转发数  随机10以内
            headline.setRepinCount(headline.getRepinCount() + random.nextInt(10));
            //点赞数  随机1-26
            headline.setThumpUpNum(headline.getThumpUpNum() + random.nextInt(25)+1);
            //收藏数  随机1-10
            headline.setCollectionNum(headline.getCollectionNum() + random.nextInt(9)+1);
        }
        headlinesService.saveOrUpdateBatch(headlines);
        log.info("机器人生成百家数据任务结束,执行时间:{}",format.format(new Date()));
    }

    @Scheduled(cron = "0 0 9-17 * * ?")
    public void pushHeadlines(){
        Date date = new Date(System.currentTimeMillis() - (1000 * 60 * 30));
        Headlines headlines = headlinesService.getPushHeadlines(date);
        if(headlines == null){
            return;
        }
        PushAppUtil.pushInform("唐园视频", headlines.getTitle());
    }

}
